package com.example.train_operate.util;

import cn.hutool.core.date.DateTime;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

import static com.example.train_operate.util.FileUrlPatterns.FILE_URL_DB;
import static com.example.train_operate.util.FileUrlPatterns.FILE_URL_LOCAL;

public class LocalUpload {

    public static Result uploadFileToLocal(MultipartFile file){
        if(file ==null || file.isEmpty()){
            return Result.fail().message("请选择要上传的图片");
        }
        if(file.getSize() > 1024 * 1024 * 2){
            return Result.fail().message("图片不能大于2MB");
        }
        String contentType = file.getContentType();
        if(contentType.equals("image/jpeg") || contentType.equals("image/png") || contentType.equals("image/gif") || contentType.equals("image/jpg")){
            //获取文件名称
            String originalFilename = file.getOriginalFilename();
            //使用uuid在文件名称中添加唯一在值
            String uuid = UUID.randomUUID().toString().replace("-","");
            originalFilename = uuid + originalFilename;
            String datePath = new DateTime().toString("yyyy/MM/dd");
            originalFilename = datePath + "/" + originalFilename;
            File dest = new File(FILE_URL_LOCAL + originalFilename);
            if(!dest.getParentFile().exists()){
                //文件夹不存在，创建文件夹
                boolean mkdirs = dest.getParentFile().mkdirs();
                if(!mkdirs){
                    return Result.fail().message("文件夹创建失败");
                }
            }
            try{
                file.transferTo(dest);
                String url = FILE_URL_DB + originalFilename;
                return Result.ok(url).message("图片上传成功");
            }catch (Exception e){
                return Result.fail().message("图片上传失败");
            }
        }else {
            return Result.fail().message("图片格式错误");
        }
    }
}
